package com.ty.service;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.hutool.jwt.JWTUtil;

import cn.smart.core.exception.BizException;
import com.ty.config.EmailConfig;
import com.ty.dao.UserDao;
import com.ty.dto.LoginDTO;
import com.ty.dto.UserRegisterDTO;
import com.ty.entity.Permissions;
import com.ty.entity.Roles;
import com.ty.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserService {
    @Autowired
    private EmailConfig emailConfig;
    @Autowired
    private UserDao userDao;

    @Value("${cn.smart.tokenx.key}")
    private String jwtKey;
    //使用本地缓存来存我们的验证码
    //创建缓存，默认5分钟过期
    TimedCache<String, Integer> timedCache = CacheUtil.newTimedCache(1000*60*1);


    public int sentCode(String email) {
        MailAccount account = new MailAccount();
        account.setHost(emailConfig.getHost()); //邮箱服务器地址 ：smtp.qq.com  smtp.126.com
        account.setPort(emailConfig.getPort()); // 端口号
        account.setAuth(emailConfig.getAuth());
        account.setFrom(emailConfig.getFrom()); //发件人的邮箱  qq邮箱   2753212@qq.com
        account.setUser(emailConfig.getUser()); // qq邮箱   2753212
        account.setPass(emailConfig.getPass());
        int code = RandomUtil.randomInt(1000, 10000);
        timedCache.put(email, code);
        //String content = "您的验证码：" + code;
        StringBuilder content = new StringBuilder();
        content.append("<table border=1>");
        content.append("<tr>");
        content.append("<td>");
        content.append("您的验证码：" + code);
        content.append("</td>");
        content.append("</tr>");
        content.append("</table>");
        MailUtil.send(account, CollUtil.newArrayList(email), "验证码", content.toString(), true);
        return 0;
    }

    public int register(UserRegisterDTO userRegisterDTO) {
        //1.校验验证码
        Integer code = timedCache.get(userRegisterDTO.getEmail());
        if(!code.equals(userRegisterDTO.getCode())){
            BizException.throwException(415,"验证码错误");
        }
        //2. 校验手机号是否已经注册
        User user = userDao.check(userRegisterDTO.getTel());
        if(ObjectUtil.isNotEmpty(user)){
            BizException.throwException(416,"手机号已注册");
        }
        //3. 插入用户信息
        user = new User();
        user.setTel(userRegisterDTO.getTel());
        user.setNickName(userRegisterDTO.getNickName());
        user.setPassword(userRegisterDTO.getPassword());
        user.setEmail(userRegisterDTO.getEmail());
        user.setLastUpdateBy("");
        return userDao.insert(user);

    }

    public String login(LoginDTO loginDTO) {
        String tel = loginDTO.getTel();
        String password = loginDTO.getPassword();
        if(ObjectUtil.isEmpty(tel) || ObjectUtil.isEmpty(password)){
            BizException.throwException(415,"手机号或密码不能为空");
        }
        if(!Validator.isMobile(tel)){
            BizException.throwException(416,"手机号格式不对");
        }
        User user = userDao.login(tel, password);
        if(ObjectUtil.isEmpty(user)){
            BizException.throwException(417,"手机号或密码不正确");
        }
        //生成token jwt  业务token  刷新token
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", user.getId());
        map.put("tel", user.getTel().substring(0, 3)+"****"+user.getTel().substring(7, 11)); //脱敏  13243341212   ->  132****1212
        map.put("nickName", user.getNickName());
        map.put("roles", user.getRoles().stream().map(Roles::getName).collect(Collectors.toList()));//角色
        map.put("permissions", user.getPermissions().stream().map(Permissions::getName).collect(Collectors.toList())); //权限
        map.put("exp", System.currentTimeMillis()/1000 +   60 * 60 * 24 * 15); //过期时间 60 * 60 * 24 * 15
        String token = JWTUtil.createToken(map, jwtKey.getBytes());

        return token;
    }
}
